package com.qf.fronted.controller;

import com.qf.fronted.domain.Data;
import com.qf.fronted.domain.SmsCode;
import com.qf.fronted.service.UserService1;
import com.qf.fronted.service.impl.SmsService;
import org.apache.commons.text.RandomStringGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@CrossOrigin(origins = "*")  //跨域配置
public class SmsController {
    private SmsService smsService = new SmsService();
    private UserService1 userService1;

    public SmsController(UserService1 userService1) {
        this.userService1 = userService1;
    }

    @RequestMapping("/sms")
    @ResponseBody
    public Data getSms(HttpServletRequest req,String phone) {
        // 检测手机号是否存在
        boolean isExists = userService1.checkPhoneOrUsername(phone);
        Data data = null;
        //表示手机已经存在, 后面的内容不用执行
        if (isExists) {
            data = new Data(-2, "手机号已存在");
            return data;
        }

        //生成0到9之间的随机数字
        RandomStringGenerator generator = new RandomStringGenerator.Builder()
                .withinRange(new char[]{'0', '9'}).build();
        String code = generator.generate(4);  //随机生成长度为4位的数字
        // 短信验证码
        SmsCode smsCode = new SmsCode(code, phone, 120);
        req.getSession().setAttribute("smsCode", smsCode);
        try {
            //调用发送短信的服务
            smsService.sendSms(code, phone);
            data = new Data(1, "success");
        } catch (Exception ex) {
            ex.printStackTrace();
            data = new Data(-1, "短信发送失败");
        }
        return data;
    }

}
